package com.tedu._03vehicle.controller;

import com.tedu._03vehicle.base.response.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/files")
public class UploadController {
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //获取接收文件文件名
        String filename = file.getOriginalFilename();
        //获取文件后缀格式
        String suffix = filename.substring(filename.lastIndexOf("."));
        //生成随机唯一uid
        UUID uuid = UUID.randomUUID();
        //组合文件名
        filename = uuid+suffix;
        //设置时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
        //按时间格式获取当前时间
        String datePath = simpleDateFormat.format(new Date());
        System.out.println("filename:"+filename);
        //设置目录路径
        String dirPath = "d:/files";
        //创建目录
        File file1 = new File(dirPath+datePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //上传文件
        String filePath = dirPath+datePath+filename;
        file.transferTo(new File(filePath));
        //返回响应
        return JsonResult.success(datePath+filename);
    }
}
